<template>
  <d2-container>
    <template slot="header">
      <el-form :gutter="24" ref="search-box" :model="mainQuery" label-position="left" :inline="true" label-width="90px" v-show="showSearchBox">
        <el-row :gutter="24">

          <el-col :span="8">
            <!-- 订单号 -->
            <el-form-item :label="$t('page-trade-detail.search-box.tradeNo')" size="mini">
              <el-input placeholder="" v-model="mainQuery.tradeNo" @keyup.enter.native="fetchMainData" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 退款状态 -->
            <el-form-item :label="$t('page-trade-detail.search-box.isRefund')" size="mini">
              <el-select v-model="mainQuery.isRefund" clearable>
                <el-option v-for="item in isRefundOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 冻结状态 -->
            <el-form-item :label="$t('page-trade-detail.search-box.isFrozen')" size="mini">
              <el-select v-model="mainQuery.isFrozen" clearable>
                <el-option v-for="item in isFrozenOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 解冻状态 -->
            <el-form-item :label="$t('page-trade-detail.search-box.isThaw')" size="mini">
              <el-select v-model="mainQuery.isThaw" clearable>
                <el-option v-for="item in isThawOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 拒付状态 -->
            <el-form-item :label="$t('page-trade-detail.search-box.isDishonour')" size="mini">
              <el-select v-model="mainQuery.isDis" clearable>
                <el-option v-for="item in isDisOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 持卡人邮箱 -->
            <el-form-item :label="$t('page-trade-detail.search-box.cardEmail')" size="mini">
              <el-input placeholder="" v-model="mainQuery.cardEmail" @keyup.enter.native="fetchMainData" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- IP -->
            <el-form-item :label="$t('page-trade-detail.search-box.ipAddress')" size="mini">
              <el-input placeholder="" v-model="mainQuery.ipAddress" @keyup.enter.native="fetchMainData" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 持卡人手机 -->
            <el-form-item :label="$t('page-trade-detail.search-box.cardPhone')" size="mini">
              <el-input placeholder="" v-model="mainQuery.cardFullPhone" @keyup.enter.native="fetchMainData" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 持卡人姓名 -->
            <el-form-item :label="$t('page-trade-detail.search-box.cardFullName')" size="mini">
              <el-input placeholder="" v-model="mainQuery.cardFullName" @keyup.enter.native="fetchMainData" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 交易时间 -->
        <el-form-item :label="$t('page-trade-detail.search-box.createTime')" size="mini">
          <el-date-picker v-model="dateTimeRange" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" @change="onDateTimePickerChange" :start-placeholder="$t('page-trade-detail.search-box.startDate')" :end-placeholder="$t('page-trade-detail.search-box.endDate')">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div class="search-btn-box">
        <div class="left">
          <!-- 展开 | 关闭 -->
          <el-link type="primary" size="mini" :icon="showSearchBox ? 'el-icon-top' : 'el-icon-bottom'" @click="showSearchBox = !showSearchBox">{{
              showSearchBox
                ? $t("page-trade-detail.search-box.close")
                : $t("page-trade-detail.search-box.expand")
            }}</el-link>

            <el-button style="margin-left: 20px;" class="filter-item" icon="el-icon-download" size="mini" @click="handleExportExcel">{{$t('page.form.export')}}</el-button>

        </div>

        <div class="right">
          <!-- 重置 -->
          <el-button class="filter-item" size="mini" icon="el-icon-refresh" type="default" @click="resetMainData" :loading="mainTable.loading">{{ $t("page.search-box.reset") }}</el-button>
          <!-- 搜索 -->
          <el-button class="filter-item" size="mini" icon="el-icon-search" type="primary" @click="fetchMainData">{{ $t("page.search-box.search") }}</el-button>
        </div>
      </div>
    </template>

    <!--主列表数据-->
    <d2-crud-x ref="d2Crud" :options="mainTable.options" :index-row="mainTable.indexRow" :columns="mainTable.columns" :data="mainTable.list" :selection-row="mainTable.allowSelect" :loading="mainTable.loading" :rowHandle="mainTable.rowHandle" @current-change="onMainCurrentChange" @custom-emit-handle-order="handleOrderDetail" @custom-emit-handle-refund="refundOrder" @selection-change="handleSelectionChange"></d2-crud-x>

    <template slot="footer">
      <el-pagination @size-change="handleMainSizeChange" @current-change="handleMainPageChange" :current-page="mainTable.pagination.currentPage" :page-sizes="mainTable.pagination.pageSizes" :page-size="mainTable.pagination.pageSize" :page-count="mainTable.pagination.pageCount" :total="mainTable.pagination.total" layout="total, sizes, prev, pager, next, jumper" :background="true">
      </el-pagination>
    </template>

    <dialog-info ref="dialog-info" @dialog-close="fetchMainData"></dialog-info>

    <dialog-refund ref="dialog-refund" @dialog-close="fetchMainData"></dialog-refund>

    <common-export ref="common-export"></common-export>

  </d2-container>
</template>

<script>
import i18nTable from "@/mixins/i18n-table";
import ApiMain from "@/api/trade.detail";
import DialogAdd from "./dialog-info";
import DialogRefundl from "./dialog-refund";
import util from "@/libs/util.js";
import ChannelApiMain from "@/api/bank.channel";

export default {
  name: "trade-detail",
  mixins: [i18nTable],
  components: {
    "dialog-info": DialogAdd,
    "dialog-refund": DialogRefundl,
  },
  data() {
    return {
      mainQuery: {
        mchNo: "",
        terNo: "",
        tradeNo: "",
        isRefund: "",
        isChecked: "",
        isSettle: "",
        isShip: "",
        isDis: "",
        isFrozen: "",
        isThaw: "",
        channelId: "",
        cardType: "",
        transStatus: "",
        cardEmail: "",
        cardFullName: "",
        cardFullPhone: "",
        ipAddress: "",
        startTime: "",
        endTime: "",
      },

      mainTable: {
        loading: false,
        options: {
          border: true,
          stripe: true,
          highlightCurrentRow: true,
          emptyText: "暂无数据",
          t: "page-trade-detail.d2-crud.empty-data",
          size: "mini",
        },
        // indexRow: {
        //   title:'序号',
        //   width: "80",
        //   align:'center'
        // },
        indexRow: null,
        columns: [
          // 单号
          {
            title: "单号",
            t: "page-trade-detail.d2-crud.column-tradeNo",
            key: "tradeNo",
            align: "center",
            minWidth: "180",
            showOverflowTooltip: true,
            fixed: true,
          },
          // 交易时间
          {
            title: "交易时间",
            t: "page-trade-detail.d2-crud.column-createTime",
            key: "createTime",
            align: "center",
            minWidth: "180",
            showOverflowTooltip: true,
          },


          // 交易金额
          {
            title: "交易金额",
            t: "page-trade-detail.d2-crud.column-mchTransAmount",
            key: "mchTransAmount",
            align: "center",
            minWidth: "140",
            showOverflowTooltip: true,
            formatter(row, column, cellValue, index) {
              return (
                row.mchTransCurrency +
                " " +
                (row.mchTransAmount / 100).toFixed(2)
              );
            },
          },

          {
            title: "商户结算金额",
            t: "page-trade-detail.d2-crud.column-settleAmount",
            key: "settleAmount",
            align: "center",
            minWidth: "140",
            showOverflowTooltip: true,
            formatter(row, column, cellValue, index) {
              return (
                row.settleCurrency +
                " " +
                (row.settleAmount / 100).toFixed(2)
              );
            },
          },
          {
            title: "支付方式",
            t: "page-trade-detail.d2-crud.column-payType",
            key: "strChannelType",
            align: "center",
            minWidth: "180",
            showOverflowTooltip: true,
          },
          // 交易状态
          {
            title: "交易状态",
            t: "page-trade-detail.d2-crud.column-transStatus",
            key: "strTransStatus",
            align: "center",
            minWidth: "140",
            showOverflowTooltip: true,
          },
        ],
        rowHandle: {
          width: "230",
          align: "center",
          fixed: "right",
          t: "page.form.operation",
          columnHeader: this.$t('page.form.operation'),
          custom: [
            {
              text: "订单详情",
              t: "page-trade-detail.d2-crud.column-detail",
              type: "default",
              size: "mini",
              emit: "custom-emit-handle-order",
            },
            {
              text: "退款",
              t: "page-trade-detail.d2-crud.column-Refund",
              type: "primary",
              size: "mini",
              disabled(index, row) {
                // 支付成功，且不能在退款中
                return !(row.transStatus == 6 && row.isRefund != 1 && row.isRefund != 2 && row.isRefund != 4 &&
                  row.isDis != 1 && row.isDis != 2 && row.isDis != 4 &&
                  row.isFrozen != 1 && row.isFrozen != 2 && row.isFrozen != 4);
              },
              emit: "custom-emit-handle-refund",
            },
          ],
        },
        list: [],
        pagination: {
          currentPage: 1,
          pageSize: 50,
          total: 0,
          pageSizes: [50, 100, 200],
        },
      },

      isRefundOptions: [],
      isFrozenOptions: [],
      isSettleOptions: [],
      isDisOptions: [],
      isThawOptions: [],
      channelIdOptions: [],
      dateTimeRange: [],
      selectionList: [],
      showSearchBox: false,
    };
  },

  mounted() {
    this.fetchOptions();
    this.fetchChannelOptions();
    this.resetMainData();
  },
  beforeDestroy() { },
  methods: {
    handleSelectionChange(selection) {
      this.selectionList = selection;
    },
    refundOrder(val) {
      this.$refs["dialog-refund"].show(val.row);
    },
    renderMainData(re) {

      this.mainTable.list = re.list;
      this.mainTable.pagination.total = re.total;
    },

    handleMainSizeChange(val) {
      this.mainTable.pagination.pageSize = val;
      this.fetchMainData();
    },
    handleMainPageChange(val) {
      this.mainTable.pagination.currentPage = val;
      this.fetchMainData();
    },

    buildMainQuery() {
      var query = {
        page: this.mainTable.pagination.currentPage,
        limit: this.mainTable.pagination.pageSize,
        search: this.mainQuery,
      };

      return query;
    },

    resetMainData() {
      this.mainQuery = {
        mchNo: "",
        terNo: "",
        tradeNo: "",
        isRefund: "",
        isChecked: "",
        isSettle: "",
        isShip: "",
        isDis: "",
        isFrozen: "",
        isThaw: "",
        channelId: "",
        cardType: "",
        transStatus: "",
        cardEmail: "",
        cardFullName: "",
        cardFullPhone: "",
        ipAddress: "",
        startTime: "",
        endTime: "",
      };

      this.fetchMainData();
    },

    fetchChannelOptions() {
      // ChannelApiMain.option().then((re) => {
      //   this.channelIdOptions = re;
      // });
    },

    async fetchOptions () {
      var re = await ApiMain.isDisOptions();
      this.isDisOptions = re;

      var re = await ApiMain.isRefundOptions();
      this.isRefundOptions = re;

      var re = await ApiMain.isFrozenOptions();
      this.isFrozenOptions = re;

      var re = await ApiMain.isThawOptions();
      this.isThawOptions = re;

      var re = await ApiMain.isSettleOptions();
      this.isSettleOptions = re;
    },

    async fetchMainData() {
      this.mainTable.loading = true;

      try {
        var re = await ApiMain.list(this.buildMainQuery());
        this.renderMainData(re);
      } catch (err) { }

      this.mainTable.loading = false;
    },

    onDateTimePickerChange() {
      this.mainQuery.startTime =
        this.dateTimeRange && this.dateTimeRange.length > 0
          ? this.dateTimeRange[0]
          : "";
      this.mainQuery.endTime =
        this.dateTimeRange && this.dateTimeRange.length > 0
          ? this.dateTimeRange[1]
          : "";
    },

    onMainCurrentChange(now, old) {
      this.mainTable.current = now;
    },

    onMainDoubleClick(now) {
      this.mainTable.current = now;
      this.handleSet();
    },

    handleAdd() {
      this.$refs["dialog-info"].show();
    },

    handleSet() {
      if (this.mainTable.current) {
        this.$refs["dialog-info"].show(this.mainTable.current.id);
      } else {
        // this.$message({message: '请选择一行数据', type: 'warning'});
      }
    },

    handleOrderDetail({ index, row }) {
      this.$refs["dialog-info"].show(row.id);
    },

    handleExportExcel () {
      this.$refs['common-export'].handleExportExcel(ApiMain, this.mainQuery, true);
    },


  },
};
</script>

<style lang="scss" scope>
.item-left {
  margin-left: 20px;
}
</style>
